package com.dbsop.transport;

import com.dbsop.common.util.HostsUtils;
import com.dbsop.config.EsClientConfig;
import com.dbsop.config.EsTransportConfiguration;
import com.dbsop.mapper.ESBaseMapper;
import com.dbsop.operation.field.TcFieldOperation;
import com.dbsop.operation.index.TcIndexOperation;
import com.dbsop.request.ClientOpt;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class TcOpt extends ClientOpt {


    private TransportClient transportClient;

    public TcOpt(EsClientConfig esClientConfig, List<ESBaseMapper> esBaseMappers) {
        super(esClientConfig, esBaseMappers);

    }

    @Override
    protected void initOperation() {
        this.clientRequest = new TcRequest(transportClient);
        this.fieldOperation = new TcFieldOperation(transportClient);
        this.indexOperation = new TcIndexOperation(transportClient);
    }


    public void initClient(){
        EsTransportConfiguration config = esClientConfig.getTransport();
        if(config == null) return ;
        List<TransportAddress> servers = new ArrayList<TransportAddress>();
        config.getHosts().forEach(host -> {
            servers.add(HostsUtils.getTransportAddress(host));
        });

        Settings.Builder setBuilder = Settings.builder()
                .put("client.transport.sniff", true)
                .put("cluster.name", config.getClusterName());
        config.getSetting().forEach((key, val) -> setBuilder.put(key,val));
        Settings setttings = setBuilder.build();//集群名字
        PreBuiltTransportClient client = new PreBuiltTransportClient(setttings);

        servers.forEach(server->{
            client.addTransportAddress(server);
        });
        transportClient= client;
    }

    public TransportClient getTransportClient() {
        return transportClient;
    }



}
